<?php


namespace app\admin\controller;


use app\admin\model\AdminLogModel;
use app\admin\model\OrderInfoModel;
use app\admin\model\RoleUserModel;
use app\admin\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;

class OrderController extends AdminBaseController
{
    public function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $role_id = RoleUserModel::where('user_id', $admin_id)->value('role_id');
        $role_id = $role_id ? $role_id : 1;
        $this->assign('role_id', $role_id);
        if ($this->request->isAjax()) {
            $data = $this->request->param();
            $page = isset($data['page']) && $data['page'] ? intval($data['page']) : 1;
            $num = 10;
            $admin_id = cmf_get_current_admin_id();
            $admin_info = UserModel::get($admin_id);
            $where = [];
            if ($admin_info['company_id']) {
                $where[] = ['company_id', '=', $admin_info['company_id']];
            } else {
                $company_id = isset($data['company_id']) && $data['company_id'] ? $data['company_id'] : '';
                if ($company_id) {
                    $where[] = ['company_id', '=', $company_id];
                }
            }
            if (isset($data['duration']) && $data['duration']) {
                $where[] = ['create_time', 'between time', [$data['duration'][0], $data['duration'][1]]];
            }
            if (isset($data['order_status'])) {
                $where[] = ['order_status', '=', $data['order_status']];
            }
            if (isset($data['pay_status'])) {
                $where[] = ['pay_status', '=', $data['pay_status']];
            }
            if (isset($data['shipping_status'])) {
                $where[] = ['shipping_status', '=', $data['shipping_status']];
            }
            $list = OrderInfoModel::withCount('admin_log')->with(['company', 'user_info', 'order_goods_list', 'coupon_info', 'refund_info', 'admin_log' => function ($query) {
                $query->with('user_info')->order('create_time desc');
            }])->where($where)
                ->order('create_time desc')
                ->paginate($num, false, ['page' => $page])->each(function ($item) {
                    if ($item['card_code']) {
                        $card_param['company_id'] = $item['company_id'];
                        $card_param['code'] = $item['card_code'];
                        $card_param['card_id'] = $item['card_id'];
                        $card_status = hook('check_card_status', $card_param);
                        $item['card_status'] = $card_status;
                        if ($card_status[0]['errcode'] == 0) {
                            if ($card_status[0]['can_consume'] == false) {
                                $item['coupon_status'] = '卡券状态异常';
                            } else {
                                $item['coupon_status'] = '未使用';
                            }
                        } else {
                            $item['coupon_status'] = '已使用';
                        }
                    }
                    return $item;
                });
            $this->success('', '', $list);
        }
        return $this->fetch();
    }

    public function change_price()
    {
        if ($this->request->isPost()) {
            try {
                Db::startTrans();
                $data = $this->request->param();
                $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
                $price = isset($data['price']) && $data['price'] ? $data['price'] : '';
                if (empty($price)) {
                    throw new Exception('请输入修改后的价格');
                }
                $order_info = OrderInfoModel::where('order_sn', $order_sn)->find();
                if (empty($order_info)) {
                    throw new Exception('订单不存在');
                }
                if ($order_info['pay_status'] != '待支付') {
                    throw new Exception('订单状态异常');
                }
                $before_real_price = $order_info['real_price'];
                if ($before_real_price == $price) {
                    throw new Exception('价格未做调整');
                }
                $order_info->real_price = $price;
                $res = $order_info->save();
                if ($res) {
                    $admin_log = new AdminLogModel([
                        'admin_id' => cmf_get_current_admin_id(),
                        'type' => 0,
                        'remark' => '修改订单' . $order_sn . '价格,' . '由' . $before_real_price . '调整为' . $price,
                        'order_sn' => $order_sn,
                        'before_order_price' => $before_real_price,
                        'now_order_price' => $price,
                    ]);
                    $admin_log->save();
                    Db::commit();
                    $this->error('修改价格成功');
                } else {
                    throw new Exception('修改价格失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


        }
    }

    public function express()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
            $order_info = OrderInfoModel::where('order_sn', $order_sn)->find();
            if (empty($order_info)) {
                $this->error('订单不存在');
            }
            $order_info->shipping_status = 1;
            $order_info->express_name = $data['express_name'];
            $order_info->express_number = $data['express_number'];
            $order_info->shipping_time = time();
            $res = $order_info->save();
            if ($res) {
                $this->success('发货成功');
            } else {
                $this->error('发货失败');
            }
        }
    }

    public function refund()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
            $order_info = OrderInfoModel::where('order_sn', $order_sn)->find();
            if (empty($order_info)) {
                $this->error('订单不存在');
            }
            $refund_money = isset($data['refund_money']) && $data['refund_money'] ? $data['refund_money'] : 0;
            if ($refund_money <= 0 || $refund_money > $order_info['money_paid']) {
                $this->error('退款金额错误');
            }
            $refund_reason = isset($data['refund_reason']) && $data['refund_reason'] ? $data['refund_reason'] : '';
            $refund_order_sn = "REFUND_" . cmf_get_order_sn();
            $order_info->refund_money = $refund_money;
            $order_info->refund_reason = $refund_reason;
            $order_info->refund_order_sn = $refund_order_sn;
            $order_info->refund_time = time();
            $param['company_id'] = $order_info['company_id'];
            $param['order_sn'] = $order_info['pay_sn'];
            $param['total_money'] = $order_info['money_paid'] * 100;
            $param['refund_money'] = $refund_money * 100;
            $param['refund_order_sn'] = $refund_order_sn;
            $param['desc'] = $refund_reason;
            $res = hook('wechat_web_refund', $param);
            if ($res[0]['return_code'] == 'SUCCESS' && $res[0]['return_msg'] == 'OK' && $res[0]['result_code'] == 'SUCCESS') {
                $order_info->pay_status = 3;
                $order_info->save();
                $this->success('退款成功', '', $res);
            } else {
                $this->error('退款失败', '', $res);
            }

        }
    }
}
